package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1007 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int minDominoRotations(int[] tops, int[] bottoms) {
            int[] cnt = new int[7];
            for (int top : tops) cnt[top]++;
            for (int bottom : bottoms) cnt[bottom]++;

            int candidate = -1, stepTop = 0, stepBottom = 0;
            for (int i = 1; i < 7; i++) {
                if (cnt[i] >= tops.length) {
                    candidate = i;
                    break;
                }
            }

            if (-1 == candidate) return -1;
            // 尝试反转 top
            for (int i = 0; i < tops.length; i++) {
                if (tops[i] == candidate) continue;
                else if (bottoms[i] != candidate) {
                    stepTop = Integer.MAX_VALUE;
                    break;
                } else stepTop++;
            }

            // 尝试反转 bottoms
            for (int i = 0; i < bottoms.length; i++) {
                if (bottoms[i] == candidate) continue;
                else if (tops[i] != candidate) {
                    stepBottom = Integer.MAX_VALUE;
                    break;
                } else stepBottom++;
            }

            int ans = Math.min(stepBottom, stepTop);
            return ans == Integer.MAX_VALUE ? -1 : ans;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.minDominoRotations(InputUtil.toIntegerArray("[2,1,2,4,2,2]"), InputUtil.toIntegerArray("[5,2,6,2,3,2]")));
        System.out.println(solution.minDominoRotations(InputUtil.toIntegerArray("[3,5,1,2,3]"), InputUtil.toIntegerArray("[3,6,3,3,4]")));
    }

    public static void main(String[] args) throws Exception {
        LC1007 an = new LC1007();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
